package com.javaee.web.servlet;
import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaee.ejb.entity.Conversation;
import com.javaee.ejb.entity.ConversationMessage;
import com.javaee.ejb.jms.remote.ConversationMessageQueueSenderRemote;
import com.javaee.ejb.session.remote.ConversationManagerRemote;
import com.javaee.ejb.session.remote.EmployeeManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

/**
 * Servlet implementation class AddMessage
 */
public class AddMessageServlet extends HttpServletBase {
	private static final long serialVersionUID = 1L;

	@EJB
	private ConversationManagerRemote conversationManager;
	@EJB
	private EmployeeManagerRemote employeeManager;
	@EJB
	private ConversationMessageQueueSenderRemote queueSender;

	/**
	 * @see HttpServletBase#HttpServletBase()
	 */
	public AddMessageServlet() {
		super();
	}

	@Override
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int conversationId;
		int senderId;
		int receiverId;
		try {
			conversationId = Integer.parseInt(request
					.getParameter("conversationId"));
			senderId = Integer.parseInt(request.getParameter("senderId"));
			receiverId = Integer.parseInt(request.getParameter("receiverId"));
		} catch (Exception e) {
			throw new ServletException(e.getMessage());
		}
		String content = request.getParameter("content").trim();

		if (content.length() > 0) {
			// Recuperation de la conversation
			Conversation conversation = conversationManager
					.getById(conversationId);

			// Creation du message
			ConversationMessage message = new ConversationMessage();
			message.setContent(content);
			message.setConversation(conversation);
			message.setReceiver(employeeManager.getById(receiverId));
			message.setSender(employeeManager.getById(senderId));
			message.setTime(new Date());

			queueSender.postMessage(message);
		}

		response.sendRedirect(SiteParameters.getFullServletPath("cortexTalk")
				+ "?conversationId=" + conversationId);
	}
}
